package cn.com.surker.material.service.impl;

import cn.com.surker.common.Code;
import cn.com.surker.material.dao.MainMaterialDao;
import cn.com.surker.material.dao.MainMaterialWeightDao;
import cn.com.surker.material.entity.MainMaterial;
import cn.com.surker.material.entity.MainMaterialWeight;
import cn.com.surker.material.service.MainMaterialService;
import cn.com.surker.oa.dao.OaMaterialDao;
import cn.com.surker.oa.entity.OaMaterial;
import cn.com.surker.util.StringUtils;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author lucky
 * @create 2024年07月04 7:46
 * @desc
 */
@Slf4j
@Service
public class MainMaterialServiceImpl implements MainMaterialService {

    @Resource
    private MainMaterialDao mainMaterialDao;
    @Resource
    private OaMaterialDao oaMaterialDao;
    @Resource
    private MainMaterialWeightDao mainMaterialWeightDao;

    /**
     * 查询所有
     * @return
     */
    public List<OaMaterial> findAll() {
        QueryWrapper<OaMaterial> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 0);
        List<OaMaterial> list = oaMaterialDao.selectList(queryWrapper);
        if (list == null || list.size() == 0)
            return null;
        return list;
    }

    /**
     * 查询仓位关联材料
     * @return
     */
    public List<OaMaterial> findByStorage(Long orgId) {
        QueryWrapper<OaMaterial> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 0);
        queryWrapper.inSql("id", "select material_id from sys_storage_match where status = 0 and org_id = " + orgId);
        List<OaMaterial> list = oaMaterialDao.selectList(queryWrapper);
        if (list == null || list.size() == 0)
            return null;
        return list;
    }

    /**
     * 查询公司关联材料
     * @return
     */
    public List<OaMaterial> findByOrg(Long orgId) {
        QueryWrapper<OaMaterial> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 0);
        queryWrapper.inSql("id", "select material_id from main_material where status = 0 and org_id = " + orgId);
        List<OaMaterial> list = oaMaterialDao.selectList(queryWrapper);
        if (list == null || list.size() == 0)
            return null;
        return list;
    }

    /**
     * 分页查询材料信息
     * @param searchVal 检索条件
     * @param status 是否启用
     * @param type 材料大类枚举 SysMaterialTypeEnum
     * @param materialId 材料父级ID
     * @param isDisPlay 过磅显示0显示1隐藏
     * @param storeType 仓位类型(0:无1:筒仓2:堆场)
     * @param offset
     * @param limit
     * @return
     */
    public IPage findPage(String searchVal, Integer status, Integer type, Long orgId, Long materialId, Integer isDisPlay,
                   Integer storeType, Integer offset, Integer limit) {
        PageHelper.offsetPage(offset, limit);
        QueryWrapper<MainMaterial> query = new QueryWrapper<>();
        if (StringUtils.isNull(status))
            status = 0;
        if (!StringUtils.isNull(status))
            query.eq("status", status);
        if (!StringUtils.isNull(type))
            query.eq("type", type);
        if (!StringUtils.isNull(materialId))
            query.eq("parent_id", materialId);
        if (!StringUtils.isNull(storeType))
            query.eq("store_type", storeType);
        if (!StringUtils.isNull(orgId))
            query.eq("org_id", orgId);
        if (!StringUtils.isNull(isDisPlay))
            query.eq("is_disPlay", isDisPlay);
        if (!StringUtils.isNull(searchVal))
            query.and(orderWrapper -> orderWrapper.like("name", searchVal).or()
                    .like("code", searchVal).or().like("name_norms", searchVal)
                    .or().like("norms", searchVal).or().like("remark", searchVal));
        query.orderByDesc("id");

        IPage<MainMaterial> iPage = mainMaterialDao.selectPage(new Page<>((offset + limit) /limit, limit), query);
        /**分页插件**/
        if (!StringUtils.isNull(iPage.getRecords())) {
            PageInfo pageInfo = new PageInfo(iPage.getRecords());
            if (!StringUtils.isNull(pageInfo.getTotal()))
                iPage.setTotal(pageInfo.getTotal());
        }
        return iPage;
    }

    /**
     * 新增材料信息
     * @param materialId 材料ID
     * @param orgId 公司ID
     * @param name 材料名称
     * @param norms 规格
     * @param nameNorms 名称规格
     * @param parentId 父级ID
     * @param storeType 仓位类型(0:无1:筒仓2:堆场)
     * @param remark
     * @param creater
     * @return
     */
    public Integer save(Long materialId, Long orgId,String name, String norms, String nameNorms, Long parentId,
                 Integer storeType, String remark, Integer isDisplay, String creater, String code, Integer type, Integer breedType, Integer weightBillType) {
        if (StringUtils.isAllParamNull(materialId, orgId, name, nameNorms, storeType))
            return Code.PARAM_EMPTY.getCode();
        if (!StringUtils.isNull(parentId) && parentId.longValue() == materialId.longValue()) {
            return Code.MATERIAL_PARENT_EXISTS.getCode();
        }
        QueryWrapper<MainMaterial> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("material_id", materialId);
        queryWrapper.eq("org_id", orgId);
        Integer total = mainMaterialDao.selectCount(queryWrapper);
        if (total > 0)
            return Code.MATERIAL_REPEAT_ADD.getCode();
        Date nowDate = new Date();
        MainMaterial mainMaterial = new MainMaterial(materialId, orgId, code, name, norms, nameNorms, parentId, storeType,
                0, remark, creater, null, nowDate);
        mainMaterial.setType(type);
        mainMaterial.setBillWeightType(weightBillType);
        mainMaterial.setBreedType(breedType);
        mainMaterial.setIsDisplay(0);
        Integer resultCode = mainMaterialDao.insert(mainMaterial);
        if (resultCode > 0)
            return 0;
        return -1;
    }

    /**
     * 修改材料信息
     * @param id
     * @param materialId 材料ID
     * @param orgId 公司ID
     * @param name 材料名称
     * @param norms 规格
     * @param nameNorms 名称规格
     * @param parentId 父级ID
     * @param storeType 仓位类型(0:无1:筒仓2:堆场)
     * @param remark
     * @param updator
     * @return
     */
    public Integer update(Long id, Long materialId, Long orgId,String name, String norms, String nameNorms, Long parentId,
                   Integer storeType, String remark, Integer isDisplay, String updator, String code, Integer type,
                          Integer breedType, Integer weightBillType, Integer isAdmin) {
        if (StringUtils.isAllParamNull(id, orgId))
            return Code.PARAM_EMPTY.getCode();
        Date nowDate = new Date();
        MainMaterial material = mainMaterialDao.selectById(id);
        if (material == null)
            return Code.ERROR_DATA.getCode();
        if (!StringUtils.isNull(materialId)) {
            QueryWrapper<MainMaterialWeight> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status", 0);
            queryWrapper.eq("material_id", material.getMaterialId());
            Integer total = mainMaterialWeightDao.selectCount(queryWrapper);
            if (total > 0) {
                if (isAdmin == 0)
                    return Code.MATERIAL_WEIGHT_EXISTS.getCode();
            }
            material.setMaterialId(materialId);
        }
        if (!StringUtils.isNull(materialId) && material.getMaterialId().intValue() != materialId.intValue()) {
            if (!StringUtils.isNull(parentId) && parentId.longValue() == materialId.longValue()) {
                return Code.MATERIAL_PARENT_EXISTS.getCode();
            }
            QueryWrapper<MainMaterial> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("material_id", materialId);
            queryWrapper.eq("org_id", orgId);
            Integer total = mainMaterialDao.selectCount(queryWrapper);
            if (total > 0)
                return Code.MATERIAL_REPEAT_ADD.getCode();
        }
        if (!StringUtils.isNull(orgId))
            material.setOrgId(orgId);
        if (!StringUtils.isNull(name))
            material.setName(name);
        if (!StringUtils.isNull(nameNorms))
            material.setNameNorms(nameNorms);
        if (!StringUtils.isNull(norms))
            material.setNorms(norms);
        if (!StringUtils.isNull(parentId))
            material.setParentId(parentId);
        if (!StringUtils.isNull(storeType))
            material.setStoreType(storeType);
        if (!StringUtils.isNull(remark))
            material.setRemark(remark);
        if (!StringUtils.isNull(isDisplay))
            material.setIsDisplay(isDisplay);
        if (!StringUtils.isNull(type))
            material.setType(type);
        if (!StringUtils.isNull(code))
            material.setCode(code);
        if (!StringUtils.isNull(weightBillType))
            material.setBillWeightType(weightBillType);
        if (!StringUtils.isNull(breedType))
            material.setBreedType(breedType);
        material.setUpdator(updator);
        material.setUpdateTime(nowDate);
        Integer resultCode = mainMaterialDao.updateById(material);
        if (resultCode > 0)
            return 0;
        return -1;
    }

    /**
     * 修改状态信息
     * @param id
     * @param status
     * @return
     */
    public Integer updateStatus(Long id, Integer status) {
        if (StringUtils.isAllParamNull(id, status))
            return Code.PARAM_EMPTY.getCode();

        MainMaterial mainMaterial = mainMaterialDao.selectById(id);
        if (mainMaterial == null)
            return Code.ERROR_DATA.getCode();
        QueryWrapper<MainMaterialWeight> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 0);
        queryWrapper.eq("material_id", mainMaterial.getMaterialId());
        Integer total = mainMaterialWeightDao.selectCount(queryWrapper);
        if (total > 0)
            return Code.WEIGHT_DATA_EXISTS_NOT_DELETE.getCode();
        mainMaterial.setStatus(status);
        Integer resultCode = mainMaterialDao.updateById(mainMaterial);
        if (resultCode > 0)
            return 0;
        return -1;
    }

    @Override
    public List<MainMaterial> getListMaterialByOrgId(Long orgId) {
        List<MainMaterial> list = new ArrayList<>();
        if(ObjectUtil.isEmpty(orgId)){
            return list;
        }
        QueryWrapper<MainMaterial> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(MainMaterial::getOrgId,orgId);
        list = mainMaterialDao.selectList(queryWrapper);
        return list;
    }

    /**
     * 根据供应商ID标识获取材料信息
     * @param supplerId
     * @return
     */
    public List<MainMaterial> findSupplierMaterial(Long orgId, Long supplerId) {
        if (StringUtils.isAllParamNull(supplerId, orgId))
            return null;
        QueryWrapper<MainMaterial> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 0);
        queryWrapper.eq("org_id", orgId);
        if (StringUtils.isNull(supplerId))
            queryWrapper.inSql("material_id", "select material_id from main_material_contract_price " +
                " where status = 0 and org_id = " + orgId + " and supplier_id = " + supplerId);
        List<MainMaterial> list = mainMaterialDao.selectList(queryWrapper);
        return list;
    }
}
